/*
location.href = '/#/performance/pay-info?order=2019051416004400002'
*/
import { Dialog } from 'vant'
var divId = 'lianlianpayform-box'
var callbackurl = 'http://paymessage.tuxiaozhu.com'
var getLianLianPay = (cb) => {
    var divInner = `
        <iframe id="lianlianpayformIframe" style="position: fixed;top: 0px;left: 0px;width: 100%;height: 100%;background: #fff;border-width: 0px;z-index: 9999;" src="http://payto.tuxiaozhu.com"></iframe>
    `
    var div
    if(!window[divId]){
        div = document.createElement('div')
        div.id = divId
    }else{
        div = window[divId]
    }
    div.innerHTML = divInner
    document.body.append(div)
    let iframeObj =  document.getElementById('lianlianpayformIframe')
    iframeObj.onload = () => {
        window.setTimeout(() => {
            cb && cb(iframeObj)
        }, 200)
    }
}
let payMessageToken = []
/**
 * 支付函数
 * @param {interface {
 *  url: string,
 *  params: any
 * }} fetchCorder 再来一单的数据，url是请求套接字，params请求参数
 * @param {number} payType 支付类型
 * @param {any} payData 支付信息，微信和支付宝，连连不大一样
 * @param {string} outTradeNo 订单号，给支付完成的页面使用
 * @param {any} cb 回调，支付完成后不进行任何处理, 这个执行比divcb慢，也就是有divcb参数就不会执行这个
 * @param {any} errcb 错误回调
 * @param {any} divcb 自定义回调，也就是设置这个参数后支付完成之后，不会进行任何处理，直接回调
 */
export const paying = function(fetchCorder, payType, payData, outTradeNo, cb, errcb, divcb) {
	console.log('payData:' + JSON.stringify(payData));
    try {
        if(!fetchCorder.url){
            alert('fetchCorder参数异常')
            return
        }
        if(!fetchCorder.params){
            alert('fetchCorder参数异常')
            return
        }
    } catch (error) {
        alert('参数异常')
        return   
    }
    console.log('--outTradeNo--')
    console.log(outTradeNo)
    // 支付通道
    var channels = null
    var toSuccess = () => {
        // console.log('cb')
        // console.log(cb)
        // console.log(outTradeNo)
        if(cb){
            cb(outTradeNo)
            return
        }
        // console.log('to')
        // this.$router.push('/performance/pay-info?order=' + outTradeNo)
        // location.href = '/#/performance/pay-info?order=' + outTradeNo
        TESTVUE.$router.replace('/performance/pay-info?order=' + outTradeNo + '&paystatus=' + '1')
        // TESTVUE.$router.replace('/performance/pay-info?order=' + outTradeNo + '&fetch=' + encodeURI(JSON.stringify(fetchCorder)) + '&paytype=' + payType)
        // location.reload()
    }
    let toFail = () => {
        if(errcb){
            errcb()
            return
        }
        console.log('已取消支付')
        console.log(fetchCorder)
        TESTVUE.$router.replace('/performance/pay-info?order=' + outTradeNo + '&fetch=' + encodeURI(JSON.stringify(fetchCorder)) + '&paytype=' + payType + '&paystatus=' + '0')
    }
    // toFail()
    // return 
    // toSuccess()
    // return
    // 支付宝
    if(payType === 1){
        if(!window.plus){
            alert('请在APP上支付')
            return
        }
        // console.log('alipay str data')
        // console.log(payData.resultObject)
        // console.log('html plus obj ')
        // console.log(JSON.stringify(window.plus))
        // console.log(plus.payment.getChannels)
        window.plus.payment.getChannels((channels) => {
            try {
                let c = channels.find(e => e.id === 'alipay') || {serviceReady: false}
                if(!c.serviceReady){
                    console.log('未安装支付宝')
                    alert("获取支付通道列表失败")
                    errcb && errcb()
                    return
                }
                window.plus.payment.request(c, payData.resultObject, () => {
                    // console.log('支付宝支付成功1')
                    if(divcb){
                        divcb()
                        return
                    }
                    // console.log('支付宝支付成功2')
                    toSuccess()                    
                }, function(e){
                    // alert("支付失败："+e.message)
                    // Dialog.alert({
                    //     title: '图小助',
                    //     message: '已取消支付宝支付'
                    // }).then(() => {
                    // })
                    toFail()
                })
            } catch (error) {
                console.log('异常')
                console.log(error)
                toFail()
        }
        }, function(e){
            Dialog.alert({
                title: '提示',
                message: '获取支付通道列表失败：'
            }).then(() => {
            })
            errcb && errcb()
        })
    }
    // 微信
    if(payType === 2){
        if(!window.plus){
            alert('请在APP上支付')
            return
        }
        console.log('weixin str data')
        console.log(JSON.stringify(payData))
        window.plus.payment.getChannels((channels) => {
            try {
                let c = channels.find(e => e.id === 'wxpay') || {serviceReady: false}
                if(!c.serviceReady){
                    console.log('未安装支付宝')
                    alert("获取支付通道列表失败")
                    errcb && errcb()
                    return
                }
                window.plus.payment.request(c, payData.data, () => {
                    if(divcb){
                        divcb()
                        return
                    }
                    toSuccess()                    
                }, function(e){
                    console.log(JSON.stringify(e))
                    // Dialog.alert({
                    //     title: '图小助',
                    //     message: '已取消微信支付'
                    // }).then(() => {
                    // })
                    toFail()
                })
            } catch (error) {
                console.log('异常')
                console.log(error)
                errcb && errcb()
        }
        }, function(e){
            console.log(e.message)
            Dialog.alert({
                title: '提示',
                message: '获取支付通道列表失败：'
            }).then(() => {
            })
            errcb && errcb()
        })
    }
    // 银联
    if(payType === 3){
        let runingN = 1
        getLianLianPay((iframeObj) => {
            if(runingN >= 3){
                document.body.removeChild(
                    document.getElementById(divId)
                )
                return 
            }
            runingN += 1
            iframeObj.contentWindow.postMessage(payData.data, '*')
            let messageCreateDate = +new Date()
            payMessageToken.push(messageCreateDate)
            let handleMessage = (e) => {
                // console.log('test')
                let TtoS = e => (+new Date() - e) / 1000
                let timeTokens = payMessageToken.map(TtoS)
                let diffTime = TtoS(messageCreateDate)
                if(e.origin !== callbackurl){
                    return
                }
                console.log(timeTokens)
                if(Math.min(...timeTokens) !== diffTime){
                    console.log('过期信息', diffTime)
                    return
                }
                console.log('接收到的信息', diffTime)
                console.log(e)
                console.log(diffTime)
                var gapVal = 'success_________success'
                var data = e.data.split(gapVal)[1]                
                if(e.data.includes(gapVal)){
                    document.body.removeChild(
                        document.getElementById(divId)
                    )
                    window.removeEventListener('message', handleMessage, false)
                    if(divcb){
                        divcb()
                        return
                    }
                    if(data){
                        toSuccess()
                        return
                    }
                    toFail()
                } 
            }
            let addMessage = () => {
                window.addEventListener('message', handleMessage, false)
            }
            addMessage()
        })
    }
    // // TODO 银联支付的话转跳第三方绑定 
    // this.$router.push('/performance/pay-info')
}